<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="JVM,并发,">










<meta name="description" content="JVM内存模型因为计算机的不断发展，程序要怎样尽量的发挥出计算机最大的性能，也成为了一个值得不断研究的问题。">
<meta name="keywords" content="JVM,并发">
<meta property="og:type" content="article">
<meta property="og:title" content="JVM内存模型">
<meta property="og:url" content="https://arrycoder.gitee.io/并发/内存模型/index.html">
<meta property="og:site_name" content="arry&#39;s blog">
<meta property="og:description" content="JVM内存模型因为计算机的不断发展，程序要怎样尽量的发挥出计算机最大的性能，也成为了一个值得不断研究的问题。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://arrycoder.gitee.io/blog/并发/内存模型/image-20200522165104469.png">
<meta property="og:image" content="https://arrycoder.gitee.io/blog/并发/内存模型/JMM.png">
<meta property="og:image" content="https://arrycoder.gitee.io/blog/并发/内存模型/image-20200608164619773.png">
<meta property="og:image" content="https://arrycoder.gitee.io/blog/并发/内存模型/threadStatus.png">
<meta property="og:updated_time" content="2020-06-16T01:17:23.342Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JVM内存模型">
<meta name="twitter:description" content="JVM内存模型因为计算机的不断发展，程序要怎样尽量的发挥出计算机最大的性能，也成为了一个值得不断研究的问题。">
<meta name="twitter:image" content="https://arrycoder.gitee.io/blog/并发/内存模型/image-20200522165104469.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://arrycoder.gitee.io/并发/内存模型/">





  <title>JVM内存模型 | arry's blog</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?97f9adfda8d04eb91dd054a98264d191";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">arry's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://arrycoder.gitee.io/blog/并发/内存模型/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="arry">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="arry's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">JVM内存模型</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2020-05-22T16:35:16+08:00">
                2020-05-22
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/并发/" itemprop="url" rel="index">
                    <span itemprop="name">并发</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="JVM内存模型"><a href="#JVM内存模型" class="headerlink" title="JVM内存模型"></a>JVM内存模型</h1><p>因为计算机的不断发展，程序要怎样尽量的发挥出计算机最大的性能，也成为了一个值得不断研究的问题。</p>
<a id="more"></a>

<p>在考虑让计算机同时执行多个任务的时候，要考虑几个问题</p>
<ol>
<li>保证每个任务的事务性，多个任务之间的状态不能因为并发导致错误。</li>
<li>因为硬盘、内存、网络等等资源之间的效率不同，要考虑如何充分利用等待的时间，去做更多的事情。</li>
</ol>
<h2 id="硬件效率和一致性"><a href="#硬件效率和一致性" class="headerlink" title="硬件效率和一致性"></a>硬件效率和一致性</h2><p>// TODO</p>
<p><img src="/blog/并发/内存模型/image-20200522165104469.png" alt="缓存模型"></p>
<h2 id="Java内存模型（Java-Memory-Model）"><a href="#Java内存模型（Java-Memory-Model）" class="headerlink" title="Java内存模型（Java Memory Model）"></a>Java内存模型（Java Memory Model）</h2><h3 id="主内存和工作内存"><a href="#主内存和工作内存" class="headerlink" title="主内存和工作内存"></a>主内存和工作内存</h3><p>Java内存模型规定了，所有的变量都必须存储在主内存上，每条线程都有自己的工作内存，线程对变量的操作只能在工作内存上进行，不能直接操作主内存的变量。不同工作线程的变量传递也是基于主内存的。</p>
<p><img src="/blog/并发/内存模型/JMM.png" alt="JMM"></p>
<h3 id="内存间的交互操作"><a href="#内存间的交互操作" class="headerlink" title="内存间的交互操作"></a>内存间的交互操作</h3><ul>
<li>lock：锁定工作线程一个对象，变成线程独占的。</li>
<li>unlock：解锁</li>
<li>read：从主内存读到工作内存</li>
<li>load：值赋给工作线程的变量副本</li>
<li>use：当字节码使用的时候use</li>
<li>assign：执行引擎赋值给工作内存的变量副本</li>
<li>store：工作内存返回给主内存</li>
<li>write：主内存更新变量</li>
</ul>
<h3 id="volatile"><a href="#volatile" class="headerlink" title="volatile"></a>volatile</h3><p>当对一个volatil对象执行写操作的时候，jvm会向处理器发送一条Lock指令，将这个变量所处的缓存行写回主内存，当一个线程改变了主内存的变量的时候，就会导致其他线程的缓存失效，需要重新从主内存读取该变量。</p>
<p>不应该频繁的读写volatile变量，因为频繁的从主内存读取数据也会影响处理器的效率。</p>
<p>内存屏障，防止重排序</p>
<h2 id="Java与线程"><a href="#Java与线程" class="headerlink" title="Java与线程"></a>Java与线程</h2><p>线程是比进程更轻量级的实现，可以把进程的资源分配和执行调度分开，线程既可以共享资源（内存地址/文件IO）也可以独立调度。</p>
<h4 id="实现线程的方式"><a href="#实现线程的方式" class="headerlink" title="实现线程的方式"></a>实现线程的方式</h4><ul>
<li><p>内核线程（KTL）</p>
<p>通常程序不会直接使用内核线程，而是使用内核线程的高级接口，轻量级进程（Light Weight Processor），每个轻量级线程都需要一个内核线程支持。</p>
<p>由内核完成切换，并通过Time Scheduler调度，将实际任务映射到 CPU内核上工作。</p>
<p>缺点是在工作的时候，如果需要进行进程操作的时候，需要将进程切回内核态，这是个非常耗费时间的操作。同时每一个轻量级进程都需要内核线程的支持，需要耗费一定的内核资源。</p>
<p><img src="/blog/并发/内存模型/image-20200608164619773.png" alt="image-20200608164619773"></p>
</li>
<li><p>用户线程</p>
<p>除了内核线程，其他线程都是用户线程。</p>
<p>无需内核提供支持，线程的创建、删除、调度等都靠程序自己实现</p>
</li>
<li><p>混合</p>
<p>两种方式都支持。</p>
</li>
</ul>
<p>在Windows和Linux系统中提供的就是一对一的线程模型，一个Java线程就对应着一个轻量级进程。</p>
<h4 id="Java线程调度"><a href="#Java线程调度" class="headerlink" title="Java线程调度"></a>Java线程调度</h4><p>两种线程调度方式</p>
<ul>
<li><p>协同式线程调度</p>
<p>当一个线程的工作结束之后，主动通知系统切换到另外一个线程去。最大的好处就是实现简单，但是如果有一个线程陷入死锁，或者一直不让出资源，就会一直阻塞在那里占着线程资源。</p>
</li>
<li><p>抢占式线程调度</p>
<p>线程的切换本身无法决定，由系统决定执行时间，这样就避免了一个线程一直堵塞着。我们可以给线程设置优先级，在两个线程处于readey状态的时候，优先级高的线程将会优先执行。</p>
</li>
</ul>
<h4 id="线程状态"><a href="#线程状态" class="headerlink" title="线程状态"></a>线程状态</h4><p>New：创建后未启动</p>
<p>Runnable：正在执行，等待分配执行时间（Running、Ready）</p>
<p>Waiting：无限期等待，除非被其他线程唤醒。</p>
<p>Time Waiting：有超时时间的等待，在timeout时间过后，由系统自动唤醒。</p>
<p>Blocked：进程被阻塞了，直到拿到排他锁才会继续执行。    </p>
<p>Terminated：线程执行结束。</p>
<p><img src="/blog/并发/内存模型/threadStatus.png" alt="image-20200528144903841"></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/JVM/" rel="tag"># JVM</a>
          
            <a href="/blog/tags/并发/" rel="tag"># 并发</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/并发/锁/" rel="next" title="锁">
                <i class="fa fa-chevron-left"></i> 锁
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/MessageQueue/RocketMQ/NameServer/" rel="prev" title="NameServer">
                NameServer <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/blog/uploads/avatar.jpg" alt="arry">
            
              <p class="site-author-name" itemprop="name">arry</p>
              <p class="site-description motion-element" itemprop="description">Java源码/设计模式/个人记录</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">42</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#JVM内存模型"><span class="nav-number">1.</span> <span class="nav-text">JVM内存模型</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#硬件效率和一致性"><span class="nav-number">1.1.</span> <span class="nav-text">硬件效率和一致性</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Java内存模型（Java-Memory-Model）"><span class="nav-number">1.2.</span> <span class="nav-text">Java内存模型（Java Memory Model）</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#主内存和工作内存"><span class="nav-number">1.2.1.</span> <span class="nav-text">主内存和工作内存</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#内存间的交互操作"><span class="nav-number">1.2.2.</span> <span class="nav-text">内存间的交互操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#volatile"><span class="nav-number">1.2.3.</span> <span class="nav-text">volatile</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Java与线程"><span class="nav-number">1.3.</span> <span class="nav-text">Java与线程</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#实现线程的方式"><span class="nav-number">1.3.0.1.</span> <span class="nav-text">实现线程的方式</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Java线程调度"><span class="nav-number">1.3.0.2.</span> <span class="nav-text">Java线程调度</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#线程状态"><span class="nav-number">1.3.0.3.</span> <span class="nav-text">线程状态</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">arry</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
